package com.example.lib_mvp.base;


import com.example.lib_mvp.base.mvp.BasePresenter;
import com.example.lib_mvp.base.mvp.BaseView;
import com.example.lib_mvp.base.mvp.HttpCallback;
import com.tjf.lib_utils.EventBusUtils;
import com.tjf.lib_utils.LogsUtils;

import org.json.JSONObject;

public abstract class AppBasePresenter<V extends BaseView> extends BasePresenter<V>
        implements HttpCallback<String> {
    public abstract void onDataBack(String url, int code, String data);

//    public abstract void onCompletes();

    @Override
    public void onSuccess(String url, String data) {
        LogsUtils.i("zmHttp=", "onSuccess-" + data);
        try {
            JSONObject jsonObject = new JSONObject(data);
            onDataBack(url, jsonObject.optInt("code") == 200 ? 0 : 1, data);
        } catch (Exception e) {
            LogsUtils.i("zmHttp=Exception",url, e.getLocalizedMessage());
            onDataBack(url, 1, "解析异常");
        }
    }

    @Override
    public void onFailure(String url, String msg) {
        LogsUtils.i("zmHttp=", "onFailure-" + msg);
        onDataBack(url, 1, msg);
    }

    @Override
    public void onError(String url, String msg) {
        LogsUtils.i("zmHttp=", "onError-" + msg);
        onDataBack(url, 1, msg);
    }

    @Override
    public void onComplete() {
        LogsUtils.i("zmHttp=", "接口请求完成 不是到是否正确---" + (getView() == null));
        if (isViewAttached())
            getView().hideLoading();
    }

    @Override
    public V getView() {
        return super.getView();
    }


    public boolean isFailActionData(String action, String data, int code) {
        if (code == 2) {
            getView().showErr();
            return true;
        }
        if (code == 1) {
            EventBusUtils.sendEvent(action, 1, data);
            return true;
        }
        return false;
    }
}
